package cn.wolfcode.demo.service.impl;

import cn.wolfcode.demo.domain.User;
import cn.wolfcode.demo.mapper.UserMapper;
import cn.wolfcode.demo.service.IUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired(required = false)
    private UserMapper userMapper;
    @Autowired
    private IUserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public User getUserByUserName(String username) {
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("username",username);
        return userMapper.selectOne(wrapper);
    }

    @Override
        public User findUserById(String id) {
            //根据Key来查redis中是否有
            String key="user"+id;
            ValueOperations<String,User> operations=redisTemplate.opsForValue();

            boolean hasKey = redisTemplate.hasKey(key);
            if(hasKey){
                //直接显示
                User user=operations.get(key);
                return user;
            }else{
                //转向mysql并存到redis
                User user = userService.getUserByUserName(id);

                //写入redis
                operations.set(key,user,5, TimeUnit.HOURS);
                return user;
            }
    }

}
